window.onload = init;

function init() {
    const canvas = $("#glcanvas")[0];
    // 初始化WebGL上下文
    const gl = WebGLUtils.setupWebGL(canvas);
  
    // 确认WebGL支持性
    if (!gl) {
      alert("无法初始化WebGL，你的浏览器、操作系统或硬件等可能不支持WebGL。");
      return;
    }
  
    // 设置视口
    gl.viewport(0, 0, canvas.width, canvas.height);
    // 使用完全不透明的黑色清除所有图像
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    
    // 加载着色器
    program = initShaders(gl, "vertexShader", "fragmentShader");
    gl.useProgram(program);

    
    // 写入数据
    var points = [
      vec2(-1,-1),
      vec2(0,1),
      vec2(1,-1),
      vec2(-1,1),
      vec2(1,1),
      vec2(0,-1)
    ];
    var colors = [
      vec4(1,0,0,1),
      vec4(0,1,0,1),
      vec4(0,0,1,1),
      vec4(0,1,0,1),
      vec4(1,0,0,1),
      vec4(0,0,1,1)
    ];
    writePoints(gl, points, "vPosition", 2);
    writePoints(gl, colors, "vColor", 4);

    // 渲染
    render(gl);
}

function render(gl) {
  // 清除缓冲区
  gl.clear(gl.COLOR_BUFFER_BIT);

  // 绘制
  gl.drawArrays(gl.TRIANGLES, 0, 3);
  //gl.drawArrays(gl.TRIANGLES, 3, 3);
}

function writePoints(gl, points, attribID, size) {
  // 绑定缓冲区
  var buffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

  // 写入数据
  gl.bufferData(gl.ARRAY_BUFFER, flatten(points), gl.STATIC_DRAW);

  // 设置着色器变量
  var attribLocation = gl.getAttribLocation(program, attribID);
  gl.vertexAttribPointer(attribLocation, size, gl.FLOAT, false, 0, 0);
  gl.enableVertexAttribArray(attribLocation);
}